package com.example.userlogin.controller;

import com.example.userlogin.dto.UserProfileResponse;
import com.example.userlogin.service.UserProfileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 用户控制器
 * 职责：处理用户相关的HTTP请求
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserProfileService userProfileService;

    /**
     * 获取当前用户资料
     */
    @GetMapping("/profile")
    public ResponseEntity<UserProfileResponse> getUserProfile() {
        logger.info("获取用户资料请求");
        
        UserProfileResponse profile = userProfileService.getCurrentUserProfile();
        
        logger.info("用户资料获取成功: {}", profile.getUsername());
        return ResponseEntity.ok(profile);
    }

    /**
     * 根据用户ID获取用户资料
     */
    @GetMapping("/profile/{userId}")
    public ResponseEntity<UserProfileResponse> getUserProfileById(@PathVariable Long userId) {
        logger.info("获取用户资料请求, ID: {}", userId);
        
        UserProfileResponse profile = userProfileService.getUserProfile(userId);
        
        logger.info("用户资料获取成功: {}", profile.getUsername());
        return ResponseEntity.ok(profile);
    }

    /**
     * 更新用户邮箱
     */
    @PutMapping("/profile/email")
    public ResponseEntity<UserProfileResponse> updateUserEmail(@RequestBody UpdateEmailRequest request) {
        logger.info("更新用户邮箱请求");
        
        UserProfileResponse currentUser = userProfileService.getCurrentUserProfile();
        UserProfileResponse updatedProfile = userProfileService.updateUserEmail(currentUser.getId(), request.getEmail());
        
        logger.info("用户邮箱更新成功: {}", updatedProfile.getUsername());
        return ResponseEntity.ok(updatedProfile);
    }

    /**
     * 更新邮箱请求DTO
     */
    public static class UpdateEmailRequest {
        private String email;

        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
    }
}